<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="referrer" content="no-referrer">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>网络收藏夹|备忘录</title>
    <link rel="icon" href="favicon.ico" type="image/x-icon"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
    <link rel="stylesheet" href="layui/css/layui.css">
    <style type="text/css">

            .layui-fixbar li:nth-child(2){
                font-size: 24px !important;
            }

			.home-icon {
				width: 30px;
				height: 30px;
				margin-top: 16px;
				margin-left: 20px;
				cursor: pointer;
			}

			.header {
			    position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 60px;
                background-color: #0A0E11;
			}

			.center {
			    position: fixed;
                width: 100%;
                top: 60px;
                bottom: 44px;
                overflow: auto;
			}

			.footer {
			    position: fixed;
                bottom: 0;
                width: 100%;
                text-align: center;
                height: 44px;
                line-height: 44px;
                background-color: #f5f7fa;
			}

			#logout {
                margin-top: 20px;
                margin-right: 20px;
                float: right;
			}

			.main {
                padding: 15px 10px;
                margin-bottom: 150px;
			}

            .notFoundDiv {
                display: none;
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }

            .notFoundDiv img {
                width: 80px;
                height: 80px;
                display: block;
                margin: 0 auto;
            }

            .notFoundDiv span{
                display: block;
                text-align: center;
                font-size: 1.5rem;
                color: #009688;
                margin-top: 24px;
                font-weight: bold;
            }

            .memorandum-item {
                position: relative;
			}

			.memorandum-item .content {
			    overflow: hidden;
			    word-break: break-all;
                white-space: pre-line;
                padding: 6px 10px;
			}

			.action {
                position: absolute;
                right: 0;
                bottom: 0;
                display:none;
			}

			.content-edit {
			    min-height: 120px;
                border: 1px solid #E4E7ED;
                background-color: #fff;
                border-radius: 4px;
                outline: 0;
                transition: all .3s;
			}

			.content-edit:hover {
			    border-color: #c0c4cc!important;
			}

			.content-edit:focus {
                border-color: #009688!important;
			}

			.content-edit + .action {
			    display:block;
			}

			.search-input {
                z-index: 999;
                position: absolute;
                top: 16px;
                right: 70px;
                width: 220px;
                height: 30px;
                transition: width .3s ease;
            }

            .search-input input {
                height: 100%;
                font-size: 12px;
                border: none;
                background-color: #161a1d;
                color: #b2b2b2;
                padding-left: 26px;
                padding-right: 26px;
            }

            .search-input .search-close {
                position: absolute;
                top: 4px;
                right: 4px;
                font-size: 20px;
                color: #666;
                display: none;
                cursor: pointer;
            }

            .search-input .search-icon {
                position: absolute;
                top: 8px;
                left: 6px;
                font-size: 14px;
                color: #999;
                cursor: pointer;
            }

            .highLight {
                background-color: rgba(255, 170, 0, 0.34);
                border: 1px solid #ffaa00;
            }

            .highLight.active {
                background-color: #c2cff9;
            }

            #search_info {
                position: absolute;
                top: 5px;
                right: 28px;
                color: #b2b2b2;
                cursor: pointer;
                display: none;
            }

    </style>
</head>
<body>
<div class="header">
    <a href="index.html"><img class="home-icon" src="images/home.svg" alt=""></a>
    <div class="search-input">
        <i id="search_icon" class="layui-icon layui-icon-search search-icon"></i>
        <input type="text" id="search_text" name="search_text" placeholder="搜索备忘录" autocomplete="off"
               class="layui-input">
        <i id="search_close" class="layui-icon layui-icon-close-fill search-close layui-anim layui-anim-fadein"
           style="display:none;"></i>
        <div id="search_info">
            <i class="layui-icon layui-icon-left" onclick="preSearch()"></i>
            <span>0/0</span>
            <i class="layui-icon layui-icon-right" onclick="nextSearch()"></i>
        </div>
    </div>
    <button class="layui-btn layui-btn-xs" type="button" id="logout">退出</button>
</div>
<div class="center" id="center">
    <div class="main">
        <div class="layui-form layui-anim layui-anim-fadein" id="addMemorandumForm" style="display:none">
            <textarea style="min-height: 200px;" name="content" required lay-verify="required" placeholder="请输入内容"
                      class="layui-textarea" wrap="hard"></textarea>
            <div class="layui-btn-container" style="text-align: right;margin-top: 10px;">
                <button class="layui-btn layui-btn-sm" lay-submit lay-filter="addMemorandum">保存</button>
                <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="cancelAddMemorandum">取消</button>
            </div>
        </div>
        <div id="memorandumDiv"><div id="memorandumList"></div></div>
    </div>
</div>
<div class="footer">
    © 2020 网络收藏夹 || 网络收藏夹版权所有
</div>
<!-- 找不到结果 -->
<div id="notFoundDiv" class="notFoundDiv">
    <img src="images/note.svg" alt="">
    <span>备忘录是空~</span>
</div>
<script src="layui/jquery-3.1.1.min.js" type="text/javascript" charset="utf-8"></script>
<script src="layui/layui.js"></script>
<script>
    layui.use(['layer','flow','util','form'], function() {
        var layer = layui.layer;
        var flow = layui.flow;
        var util = layui.util;
        var form = layui.form;

        var memorandumCount = 0;
        var searchIndex = -1;

        // 固定块
        util.fixbar({
            top: true
            ,bar1: '&#xe654;'
            ,bar2: '&#xe6dc;'
            ,scrollElem: '#center'
            ,bgcolor: '#393D49'
            ,css: {right: 50, bottom: 80}
            ,click: function(type){
                if(type === 'bar1'){
                    changeAddMemorandumMode();
                }else if(type === 'bar2'){
                    layer.msg("该功能暂未开放");
                }
            }
        });

        // 加载数据
        window.loadList = function(){
            // 加载动画
            layer.load();
            $("#memorandumList").empty();
            var keyword = $("#search_text").val().trim();
            $("#search_text").attr("data-lastSearch",keyword);
            flow.load({
                elem: '#memorandumList'
                ,scrollElem: '#center'
                ,mb: 400
                ,end: ' '
                ,done: function(page, next){
                  var lis = [];
                  $.ajax({
                        type: "GET",
                        url: "memorandum/list",
                        data: {"pageNum": page,"pageSize": 20,"content":keyword},
                        dataType: "json",
                        headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                        success: function (result) {
                            if(page == 1){// 首次加载
                                layer.closeAll('loading');
                                if(keyword && result.code == 0 && result.data.list.length > 0){
                                    searchIndex = 0;
                                }else{
                                    searchIndex = -1;
                                    $("#search_info").hide();
                                }
                            }
                            if (result.code == 0) {
                                $.each(result.data.list, function(index, item){
                                    var html = '';
                                    html += '<div class="memorandum-item layui-text" data-id="' + item.id + '">';
                                    if(keyword){
                                        html += '<div class="content" ondblclick="editContent(this)" data-keyword="'+ keyword +'">'+ wrapSearch(item.content,keyword) +'</div>';
                                    }else{
                                        html += '<div class="content" ondblclick="editContent(this)">'+ item.content +'</div>';
                                    }
                                    html += '   <div class="layui-btn-container layui-anim layui-anim-fadein action" data-id="' + item.id + '">';
                                    html += '       <button class="layui-btn layui-btn-xs saveBtn" onclick="updateContent(this)">保存</button>';
                                    html += '       <button class="layui-btn layui-btn-xs layui-btn-primary" onclick="cancelEditContent(this)">取消</button>';
                                    html += '       <button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteMemorandum(this)">删除</button>';
                                    html += '   </div>';
                                    html += '</div>';
                                    lis.push(html);
                                });
                                next(lis.join(''), page < result.data.pages);
                            }
                        }
                  });
                }
            });
        };

        loadList();


        // jQuery全局拦截器
        $(document).ajaxSuccess(function(event,xhr,options){
            var result = xhr.responseJSON;
            if(result != undefined && result.code == "401"){
                window.location.href= "login.html";
            }
        });

        // 登出
        $("#logout").click(function () {
            layer.confirm('确认退出系统吗？', function(index){
                layer.close(index);

                localStorage.clear();
                window.location.href = "login.html";
            });
        });

        // 点击空白关闭
        $(document).on("click", function(e) {
            var _conss = $('.search-input');//点击的容器范围
            if (!_conss.is(e.target) && _conss.has(e.target).length === 0) {
                $("#search_close").hide();
            }
        });

        window.preSearch = function(){
            var highLight = $(".highLight");
            var active = highLight.filter(".active");
            var index = highLight.index(active[0]);
            if(index > 0){
                active.removeClass("active");
                var pre = highLight.eq(index - 1).addClass("active");
                $("#search_info").find("span").text(index + "/" + highLight.length);
                $("#center").animate({scrollTop: pre[0].offsetTop - 100}, 50);
                searchIndex--;
            }
        };

        window.nextSearch = function(){
            var highLight = $(".highLight");
            var active = highLight.filter(".active");
            var index = highLight.index(active[0]);
            if(index < highLight.length - 1 ){
                active.removeClass("active");
                var next = highLight.eq(index + 1).addClass("active");
                $("#search_info").find("span").text((index + 2) + "/" + highLight.length);
                $("#center").animate({scrollTop: next[0].offsetTop - 100}, 50);
                searchIndex++;
            }
        };

        window.wrapSearch = function(content,keyword){
            var text = '<span class="highLight">'+keyword+'</span>';
            var reg = new RegExp(keyword,"gi");
            return content.replace(reg,text);
        };

         window.unwrapSearch = function(content,keyword){
            var text = '<span class="highLight">'+keyword+'</span>';
            var reg = new RegExp(text,"gi");
            return content.replace(reg,keyword);
        };

        // 关闭搜索
        $("#search_close").click(function () {
            $(this).hide();
            $("#search_text").val("");
            $("#search_info").hide();
            searchIndex = -1;
            loadList();
        });

        $(document).on("keydown", function(event){
            if(event.ctrlKey && event.key === "f"){
                $("#search_text").focus();
                // 阻止默认浏览器动作(W3C)
                var e = event;
                if ( e && e.preventDefault )
                    e.preventDefault();
                // IE中阻止函数器默认动作的方式
                else
                    window.event.returnValue = false;
                return false;
            }
        });

        $("#search_text").on("keydown", function(event){
            if(event.key === "Enter"){
                var noChange = $(this).val() == $(this).attr("data-lastSearch");
                if(noChange && searchIndex >= 0){
                    var highLight = $(".highLight");
                    var active = highLight.eq(searchIndex);
                    if(active[0]){
                        $("#search_info").show().find("span").text((searchIndex + 1) + "/" + highLight.length);
                        $(".highLight.active").removeClass("active");
                        active.addClass("active");
                        $("#center").animate({scrollTop: active[0].offsetTop - 100}, 50);
                        if(searchIndex < highLight.length - 1){
                            searchIndex++;
                        }else{
                            searchIndex = 0;
                        }
                    }else{
                        $("#search_info").show().find("span").text("0/0");
                    }
                }else{
                    loadList();
                }
            } else if (event.key === "Backspace") {
                // 退出选择模式
                searchIndex = -1;
            }
        }).on("focus", function () {
           $("#search_close").show();
        });

        $("#search_icon").click(function(){
            loadList();
        });

        $("#cancelAddMemorandum").click(function(){
            changeIndexMode();
        });

        window.cancelEditContent = function(obj){
            $(obj).parent().parent().find(".content").removeAttr("contenteditable").removeClass("content-edit");
        };

        window.changeAddMemorandumMode = function(){
            $("#notFoundDiv").hide();
            $("#memorandumDiv").hide();
            $("#addMemorandumForm").show();
        };

        window.changeIndexMode = function(){
            $("#addMemorandumForm").hide();
            if(memorandumCount == 0){
                $("#notFoundDiv").show();
            }else{
                $("#memorandumDiv").show();
            }
        };

        window.escapeHtml = function(html){
            return html.replace(/</g, '&lt').replace(/>/g, '&gt');
        };

        form.on('submit(addMemorandum)', function (data) {
            layer.load();
            data.field.content = data.field.content;
            $.ajax({
                type: "POST",
                url: "memorandum",
                data: JSON.stringify(data.field),
                contentType: 'application/json;charset=utf-8',
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        window.location.reload();
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                }
            });
            return false;
        });

        // 删除
        window.deleteMemorandum = function(obj){
            layer.confirm('确认删除吗?', function(index) {
                var id = $(obj).parent().attr("data-id");
                $.ajax({
                    type: "GET",
                    url: "memorandum/delete/" + id,
                    dataType: "json",
                    headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                    success: function (result) {
                        if (result.code == 0) {
                            window.location.reload();
                        }
                    }
                });
                layer.close(index);
            });
        };

        // 编辑
        window.editContent = function(obj) {
            $(".content-edit").next().find(".saveBtn").click();
            var that = $(obj);
            that.attr("contenteditable",true).addClass("content-edit").focus();
            var keyword = that.attr("data-keyword");
            if(keyword){
                that.html(unwrapSearch(that.html(),keyword));
            }
        };

        window.updateContent = function(obj){
            var contentDiv = $(obj).parent().parent().find(".content");
            contentDiv.removeAttr("contenteditable").removeClass("content-edit");
            var content = contentDiv.html();
            var id = contentDiv.parent().attr("data-id");
            $.ajax({
                type: "POST",
                url: "memorandum",
                data: JSON.stringify({"id":id,"content":content}),
                contentType: 'application/json;charset=utf-8',
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        layer.msg("保存成功", {icon: 6});
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                }
            });
        };

        $(function(){
            // 暂无数据
            $.ajax({
                type: "GET",
                url: "memorandum/count",
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    if (result.code == 0 && result.data == 0) {
                        $("#notFoundDiv").show();
                    }else{
                        memorandumCount = result.data;
                    }
                }
            });
        });
    });

</script>
</body>
</html>
